import { baseApiUrl, path } from "../../utils/config";
import { course } from '../../utils/api';
import Toast from '@vant/weapp/toast/toast';
const app = getApp();
Page({
  data: {
    baseImageUrl: baseApiUrl,
    tabs: [
      { name: "周一", value: "1" },
      { name: "周二", value: "2" },
      { name: "周三", value: "3" },
      { name: "周四", value: "4" },
      { name: "周五", value: "5" },
      { name: "周六", value: "6" },
      { name: "周日", value: "7" },
    ],
    currentIndex: null,
    day: null,

    page: 1,
    last_page: 1,
    list: []
  },
  onLoad() {
    const date = new Date();
    let day = date.getDay();
    day = day == 0 ? 7 : day;
    this.setData({ day, currentIndex: day });
    this.getList();
  },
  onReachBottom() {
    let page = this.data.page;
    let last_page = this.data.last_page;
    if (page == last_page) return false;
    page += 1;
    this.setData({ page });
    this.getList();
  },
  async getList() {
    let { day, currentIndex } = this.data;
    let res = await course({
      week: currentIndex,
      page: this.data.page,
      limit: 10
    });
    let buy_course = res.buy_course;
    res = res.course;
    let { data, last_page } = res;
    data.forEach(item => {
      let id = item.id;
      let is_buy = buy_course.includes(id);
      if (day != currentIndex) {
        item.active = true;
      } else {
        item.active = is_buy ? false : true;
      }
    })
    let list = this.data.page == 1 ? data : [...this.data.list, ...data];
    this.setData({ list, last_page })
  },
  changeTabs(e) {
    let currentIndex = e.currentTarget.dataset.key;
    this.setData({ currentIndex, list: [], page: 1 });
    this.getList();
  },
  router(e) {
    let { currentIndex, day } = this.data;
    if (currentIndex != day) {
      Toast('不在学习时间内');
      return false;
    }
    let { url } = e.currentTarget.dataset;
    wx.navigateTo({ url });
  },
  onShareAppMessage() {
    let poster = app.globalData.poster;
    return {
      path,
      imageUrl: poster
    }
  },
  onShareTimeline() { }
})